import { Cascader } from 'antd';
import React, { useEffect, useMemo, useState } from 'react';
import { SvgIcon } from '../icon';
import { DatasetListItem, DatasetTypeEnum, GetDatasetList, KnowledgeListResList } from '@/common';
import { findParentIdArray } from '@/utils/tree';
import { SelectedDatasetType } from '@/types/app/type';
const { SHOW_CHILD } = Cascader;

interface Option {
  key: string;
  value: string | number;
  label: React.ReactNode;
  name: string;
  children?: Option[];
}

const icons: Record<string, React.ReactNode> = {
  dataset: <SvgIcon icon="knowledge" size={20} />,
  folder: <SvgIcon icon="ri--folder-2-fill" size={20} />,
  function: <SvgIcon icon="interface" size={20} />,
};

const SelectDatasetCascader = ({
  datasets,
  selectedDatasets,
  onChange,
}: {
  datasets: GetDatasetList[];
  selectedDatasets: SelectedDatasetType;
  onChange: (e: SelectedDatasetType) => void;
}) => {
  const [value, setValue] = useState<string[][]>([]);

  const filter = (inputValue: string, path: Option[]) => {
    return path.some(
      (option) =>
        option?.name?.toString().includes(inputValue) ||
        (option &&
          option.children &&
          option?.children?.filter((c) => c.name.toString().includes(inputValue)).length > 0),
    );
  };

  const generateOptions = (datasets: any[]) => {
    return datasets.map((dataset) => {
      const option: Option = {
        key: dataset._id,
        value: dataset._id,
        label: (
          <div className="inline-block" style={{ verticalAlign: 'middle' }}>
            <div className="flex items-center self-center">
              {icons[dataset.type]} <span className="ml-1">{dataset.name}</span>
            </div>
          </div>
        ),
        name: dataset.name,
        children: dataset.children ? generateOptions(dataset.children) : undefined,
      };
      return option;
    });
  };

  const options = useMemo(() => {
    return generateOptions(datasets);
  }, [datasets]);

  const cvpermission = (
    allDatasets: GetDatasetList[],
    datasets: SelectedDatasetType | undefined,
  ) => {
    if (!datasets) {
      return [];
    }
    const datas: Array<string[]> = [];
    datasets.forEach((p) => {
      const array = findParentIdArray(allDatasets, p.datasetId);
      if (array) {
        datas.push([...array, p.datasetId]);
      }
    });

    return datas;
  };

  useEffect(() => {
    if (selectedDatasets) {
      const cascaderData = cvpermission(datasets, selectedDatasets);
      setValue(cascaderData);
    }
  }, [selectedDatasets, datasets]);

  return (
    <Cascader
      className="workflow-cascader"
      style={{ width: '100%' }}
      options={options}
      placeholder="选择知识库"
      multiple
      key={'_id'}
      maxTagCount="responsive"
      showCheckedStrategy={SHOW_CHILD}
      value={value}
      showSearch={{ filter }}
      dropdownClassName="workflow-dropdown"
      onChange={(value) => {
        const selectDatasets = value.map((item) => {
          return {
            datasetId: item[item.length - 1].toString(),
          };
        });
        onChange && onChange(selectDatasets);
      }}
    />
  );
};

export default React.memo(SelectDatasetCascader);
